package com.zynn.api.yinian.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

import javax.servlet.http.HttpServletResponse;

/**
 * PC端允许跨域访问的
 */
public class AccessFilter extends ZuulFilter {

    @Override
    public String filterType() {
        //请求结束之后执行
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        //表明在路由之前过滤器链中的执行顺序
        return 1;
    }

    /**
     * 表明是否需要进行路由 即是否需要执行run方法
     *
     * @return true or false
     */
    @Override
    public boolean shouldFilter() {
        //获取上下文信息
        return true;
    }

    /**
     * 允许跨域访问
     */
    @Override
    public Object run() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletResponse response = currentContext.getResponse();
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Content-Type");
        return null;
    }
}
